// https://threejs.org/examples/#webgl_loader_collada_skinning
import { 
  AmbientLight,
  AnimationAction,
  AnimationMixer,
  Clock,
  GridHelper,
  Mesh,
  MeshNormalMaterial,
  MeshStandardMaterial,
  PerspectiveCamera,
  PointLight,
  Scene, 
  TextureLoader, 
  WebGLRenderer
} from "three";
import stats from '../../utils/stats';
// 调用
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { MD2Loader } from 'three/examples/jsm/loaders/MD2Loader';
import { GUI } from 'dat.gui';

let clock = new Clock();
let scene = new Scene();
let camera = new PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000);
camera.position.set(0, 70, 100);

const renderer = new WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);

document.body.appendChild(renderer.domElement);

scene.add(new AmbientLight( 0xffffff, 0.2 ));
const lights = new PointLight(0xffffff, 0.8);
camera.add(lights);
scene.add( camera );
        
const trackballControls = new OrbitControls(camera, renderer.domElement);
// 调整场景位置
trackballControls.target.set(0, 3, 0);

let mixer: AnimationMixer;

addLoader();

render();
function render() {
  stats.update();
  trackballControls.update();

  if (mixer) {
    mixer.update(clock.getDelta())
  }

  requestAnimationFrame(render);
  renderer.render(scene, camera);
}

function addLoader() {
  const loader = new MD2Loader();
  loader.load(
    '/models/ogre/ogro.md2',
    (result: any) => {
      let { animations } = result
      let map = new TextureLoader().load('/models/ogre/skins/skin.jpg');
      let mat = new MeshStandardMaterial({
        morphTargets: true,
        color: 0xffffff,
        metalness: 0,
        map
      });
      let mesh = new Mesh(result, mat);
      scene.add(mesh);

      mixer = new AnimationMixer(mesh);
      let clipAction1 = mixer.clipAction(animations[7]);
      let clipAction2 = mixer.clipAction(animations[9]);
      let clipAction3 = mixer.clipAction(animations[10]);

      clipAction1.play();
      setGUI({
        1: clipAction1,
        2: clipAction2,
        3: clipAction3
      })

    }
  )
}

function setGUI(actions: any ) {
  const controls = {
    action: 1
  }
  let oldAction = controls.action;

  let gui = new GUI();
  gui.add(controls, 'action', [1, 2, 3]).name('动作选择').onChange(val => {
    actions[oldAction].stop();
    actions[val].play();
    oldAction = val;
  })
}